package com.xxl.job.admin.repository;

import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.core.enums.DatabaseTypeEnum;
import com.xxl.job.admin.core.model.XxlJobUser;
import com.xxl.job.admin.dao.XxlJobUserDao;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class XxlJobUserRepository implements XxlJobUserDao {
    private XxlJobUserDao xxlJobUserDao;

    public XxlJobUserRepository(XxlJobUserDao xxlJobUserDao) {
        this.xxlJobUserDao = xxlJobUserDao;
    }

    @Override
    public List<XxlJobUser> pageList(int offset, int pagesize, String username, int role) {
        return xxlJobUserDao.pageList(offset, pagesize, username, role);
    }

    @Override
    public int pageListCount(int offset, int pagesize, String username, int role) {
        return xxlJobUserDao.pageListCount(offset, pagesize, username, role);
    }

    @Override
    public XxlJobUser loadByUserName(String username) {
        return xxlJobUserDao.loadByUserName(username);
    }

    @Override
    public int save(XxlJobUser xxlJobUser) {
        DatabaseTypeEnum typeEnum = DatabaseTypeEnum.getByType(XxlJobAdminConfig.getAdminConfig().getDatabaseId());
        switch (typeEnum) {
            case MYSQL:
                return xxlJobUserDao.save(xxlJobUser);
            case ORACLE:
                // 从Oracle序列中获取ID并设值
                xxlJobUser.setId(xxlJobUserDao.getNextOracleSequenceId());
                return xxlJobUserDao.saveWithId(xxlJobUser);
            default:
                throw new RuntimeException("un support database type");
        }
    }

    @Override
    public int getNextOracleSequenceId() {
        return xxlJobUserDao.getNextOracleSequenceId();
    }

    @Override
    public int saveWithId(XxlJobUser xxlJobUser) {
        return xxlJobUserDao.saveWithId(xxlJobUser);
    }

    @Override
    public int update(XxlJobUser xxlJobUser) {
        return xxlJobUserDao.update(xxlJobUser);
    }

    @Override
    public int delete(int id) {
        return xxlJobUserDao.delete(id);
    }
}
